package com.nbcio.modules.estar.receipt.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.nbcio.modules.estar.mallorder.entity.ErpMallorder;
import com.nbcio.modules.estar.mallorder.entity.ErpMallorderB;
import com.nbcio.modules.estar.mallorder.service.IErpMallorderBService;
import com.nbcio.modules.estar.mallorder.service.IErpMallorderService;
import com.nbcio.modules.estar.rule.CesOrderRule;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.nbcio.modules.estar.receipt.entity.ErpReceiptDetail;
import com.nbcio.modules.estar.receipt.entity.ErpReceipt;
import com.nbcio.modules.estar.receipt.vo.ErpReceiptPage;
import com.nbcio.modules.estar.receipt.service.IErpReceiptService;
import com.nbcio.modules.estar.receipt.service.IErpReceiptDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 收款单主表
 * @Author: nbacheng
 * @Date: 2024-03-19
 * @Version: V1.0
 */
@Api(tags = "收款单主表")
@RestController
@RequestMapping("/receipt/erpReceipt")
@Slf4j
public class ErpReceiptController {
    @Autowired
    private IErpReceiptService erpReceiptService;
    @Autowired
    private IErpReceiptDetailService erpReceiptDetailService;
    @Autowired
    private IErpMallorderService erpMallorderService;

    @Autowired
    private IErpMallorderBService erpMallorderBService;

    /**
     * 分页列表查询
     *
     * @param erpReceipt
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "收款单主表-分页列表查询")
    @ApiOperation(value = "收款单主表-分页列表查询", notes = "收款单主表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ErpReceipt erpReceipt,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ErpReceipt> queryWrapper = QueryGenerator.initQueryWrapper(erpReceipt, req.getParameterMap());
        Page<ErpReceipt> page = new Page<ErpReceipt>(pageNo, pageSize);
        IPage<ErpReceipt> pageList = erpReceiptService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param erpReceiptPage
     * @return
     */
    @AutoLog(value = "收款单主表-添加")
    @ApiOperation(value = "收款单主表-添加", notes = "收款单主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ErpReceiptPage erpReceiptPage) {
        ErpReceipt erpReceipt = new ErpReceipt();
        BeanUtils.copyProperties(erpReceiptPage, erpReceipt);
        erpReceiptService.saveMain(erpReceipt, erpReceiptPage.getErpReceiptDetailList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param erpReceiptPage
     * @return
     */
    @AutoLog(value = "收款单主表-编辑")
    @ApiOperation(value = "收款单主表-编辑", notes = "收款单主表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody ErpReceiptPage erpReceiptPage) {
        ErpReceipt erpReceipt = new ErpReceipt();
        BeanUtils.copyProperties(erpReceiptPage, erpReceipt);
        ErpReceipt erpReceiptEntity = erpReceiptService.getById(erpReceipt.getId());
        if (erpReceiptEntity == null) {
            return Result.error("未找到对应数据");
        }
        erpReceiptService.updateMain(erpReceipt, erpReceiptPage.getErpReceiptDetailList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "收款单主表-通过id删除")
    @ApiOperation(value = "收款单主表-通过id删除", notes = "收款单主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        erpReceiptService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "收款单主表-批量删除")
    @ApiOperation(value = "收款单主表-批量删除", notes = "收款单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.erpReceiptService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "收款单主表-通过id查询")
    @ApiOperation(value = "收款单主表-通过id查询", notes = "收款单主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ErpReceipt erpReceipt = erpReceiptService.getById(id);
        if (erpReceipt == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(erpReceipt);

    }


    @AutoLog(value = "收款单主表-订单生成收款单")
    @ApiOperation(value = "收款单主表-订单生成收款单", notes = "收款单主表-订单生成收款单")
    @GetMapping(value = "/paymentId")
    public Result<?> paymentId(@RequestParam(name = "id", required = true) String id) {
        ErpMallorder erpMallorder =  erpMallorderService.getById(id);
        LambdaQueryWrapper<ErpMallorderB> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ErpMallorderB::getPkH, id);

		List<ErpMallorderB> list = erpMallorderBService.list(queryWrapper);


		if (erpMallorder == null) {
            return Result.error("未找到对应数据");
        }
        erpMallorder.setMallstatus(2);
        Date dNow = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
		ErpReceiptPage erpReceiptPage = new ErpReceiptPage();
		CesOrderRule cesOrderRule=new CesOrderRule();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("prefix", "SCSK");
		erpReceiptPage.setCode(cesOrderRule.execute(jsonObject, new JSONObject())+"");
		erpReceiptPage.setActstatus(0);
		erpReceiptPage.setCreateTime(dNow);
		erpReceiptPage.setPaymentStatus(3);
        erpReceiptPage.setCustomerId(erpMallorder.getCustomer());
        erpReceiptPage.setDef1(erpMallorder.getCustomername());
        erpReceiptPage.setDef3(erpMallorder.getCode());
        erpReceiptPage.setSaleOrderId(erpMallorder.getId());
        erpReceiptPage.setReceiptDate(ft.format(dNow));
        erpReceiptPage.setTotalAmount(erpMallorder.getMny());//收款金额
        List<ErpReceiptDetail> erpReceiptDetailList = new ArrayList<>();

        for (ErpMallorderB erpMallorderB : list) {
            ErpReceiptDetail erpReceiptDetail = new ErpReceiptDetail();
            erpReceiptDetail.setAmount(new BigDecimal(erpMallorderB.getSmuy()));
            //erpReceiptDetail.setDescription(erpMallorderB.getDescription());
            erpReceiptDetail.setSaleOrderDetailId(erpMallorderB.getId());
            erpReceiptDetail.setDef1(erpMallorderB.getNum());
            erpReceiptDetail.setDef2(erpMallorderB.getMuy());//金额
            erpReceiptDetail.setDef3(erpMallorderB.getGoodsname());
            erpReceiptDetail.setDef4(erpMallorderB.getGoodsid());
            erpReceiptDetail.setDef5(erpMallorderB.getSmuy());//总价
            erpReceiptDetail.setDef6(erpMallorderB.getNtaxrate().toString());//税率
            erpReceiptDetail.setDef7(erpMallorderB.getNtax().toString());//税额
            erpReceiptDetail.setDef8(erpMallorderB.getNqtorigtaxprice());//含税单价
            erpReceiptDetail.setDef9(erpMallorderB.getNqtorigprice());//无税单价
            erpReceiptDetailList.add(erpReceiptDetail);
        }
        ErpReceipt erpReceipt = new ErpReceipt();
        BeanUtils.copyProperties(erpReceiptPage, erpReceipt);
        erpReceiptPage.setErpReceiptDetailList(erpReceiptDetailList);
        erpReceiptService.saveMain(erpReceipt, erpReceiptPage.getErpReceiptDetailList());
        erpMallorderService.update(erpMallorder, new UpdateWrapper<ErpMallorder>().eq("id", erpMallorder.getId()));
        return Result.OK("支付成功！");

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "收款单子表通过主表ID查询")
    @ApiOperation(value = "收款单子表主表ID查询", notes = "收款单子表-通主表ID查询")
    @GetMapping(value = "/queryErpReceiptDetailByMainId")
    public Result<?> queryErpReceiptDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ErpReceiptDetail> erpReceiptDetailList = erpReceiptDetailService.selectByMainId(id);
        return Result.OK(erpReceiptDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param erpReceipt
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ErpReceipt erpReceipt) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ErpReceipt> queryWrapper = QueryGenerator.initQueryWrapper(erpReceipt, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<ErpReceipt> queryList = erpReceiptService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<ErpReceipt> erpReceiptList = new ArrayList<ErpReceipt>();
        if (oConvertUtils.isEmpty(selections)) {
            erpReceiptList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            erpReceiptList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<ErpReceiptPage> pageList = new ArrayList<ErpReceiptPage>();
        for (ErpReceipt main : erpReceiptList) {
            ErpReceiptPage vo = new ErpReceiptPage();
            BeanUtils.copyProperties(main, vo);
            List<ErpReceiptDetail> erpReceiptDetailList = erpReceiptDetailService.selectByMainId(main.getId());
            vo.setErpReceiptDetailList(erpReceiptDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "收款单主表列表");
        mv.addObject(NormalExcelConstants.CLASS, ErpReceiptPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("收款单主表数据", "导出人:" + sysUser.getRealname(), "收款单主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ErpReceiptPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ErpReceiptPage.class, params);
                for (ErpReceiptPage page : list) {
                    ErpReceipt po = new ErpReceipt();
                    BeanUtils.copyProperties(page, po);
                    erpReceiptService.saveMain(po, page.getErpReceiptDetailList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }


    @AutoLog(value = "收款单通过客户ID查询")
    @ApiOperation(value = "收款单通过客户ID查询", notes = "收款单通过客户ID查询")
    @GetMapping(value = "/queryErpReceiptDetailByCustomerId")
    public Result<?> queryErpReceiptDetailByCustomerId(@RequestParam(name = "id", required = true) String id) {
        LambdaQueryWrapper<ErpReceipt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ErpReceipt::getCustomerId, id);
        List<ErpReceipt> erpReceiptList = erpReceiptService.list(wrapper);
        if (CollectionUtil.isEmpty(erpReceiptList)) {
            return Result.OK(new ArrayList<>());
        }
        return Result.OK(erpReceiptList);
    }


}
